package com.data.util

import java.awt.*
import java.awt.image.BufferedImage
import java.util.Random

object VerificationCodeUtil {
    val AUTHCODE_LENGTH = 5// 验证码长度(个数)
    val SINGLECODE_WIDTH = 15// 单个验证码宽度
    val SINGLECODE_HEIGHT = 30// 单个验证码的高度
    val SINGLECODE_GAP = 4// 验证码之间的间隔
    val IMG_WIDTH = AUTHCODE_LENGTH * (SINGLECODE_WIDTH + SINGLECODE_GAP)
    val IMG_HEIGHT = SINGLECODE_HEIGHT
    val VERIFY_CODES = "23456789ABCDEFGHKMNPQRSTUVWXYZ"

    /**
     * 默认验证码长度的方式
     *
     * @return
     */
    // 随机生产出验证码放在auth中
    val authCode: String
        get() {
            val length = VERIFY_CODES.length
            return getCode(length)
        }


    /**
     * 自定义长度的验证码生成方式
     *
     * @param length
     * @return
     */
    // 生成验证码
    fun getAuthCode(length: Int): String {
        // 随机生产出验证码放在auth中
        return getCode(length)
    }


    private fun getCode(length: Int): String {
        val auth = StringBuilder(AUTHCODE_LENGTH)
        val random = Random()
        for (i in 0..AUTHCODE_LENGTH - 1) {
            auth.append(VERIFY_CODES[random.nextInt(length)])
        }
        return auth.toString()
    }

    // 画验证码的图片
    fun getAuthImage(authcode: String): BufferedImage {
        val img = BufferedImage(IMG_WIDTH, IMG_HEIGHT, BufferedImage.TYPE_INT_BGR)
        val g = img.graphics
        val random = Random()

        val a = random.nextInt(255)
        val b = random.nextInt(255)
        val cd = random.nextInt(255)
        val color = Color(a, b, cd)
        g.color = color
        g.fillRect(0, 0, IMG_WIDTH, IMG_HEIGHT)
        g.color = Color.black
        // 设置字体
        g.font = Font("宋体", Font.PLAIN, SINGLECODE_HEIGHT + 5)
        var c: Char
        var i = 0
        val lenght = authcode.length
        while (i < lenght) {
            c = authcode[i]
            g.drawString(c + "", i * (SINGLECODE_WIDTH + SINGLECODE_GAP) + SINGLECODE_GAP / 2, IMG_HEIGHT)
            i++

        }
        // 画干扰素
        ganRao(g)
        return img
    }

    /**
     * 绘制干扰线的方法
     *
     * @param g
     */
    private fun ganRao(g: Graphics) {
        val random = Random()
        for (i in 0..19) {
            val x = random.nextInt(IMG_WIDTH)
            val y = random.nextInt(IMG_HEIGHT)
            val x2 = random.nextInt(IMG_WIDTH)
            val y2 = random.nextInt(IMG_HEIGHT)
            g.drawLine(x, y, x + x2, y + y2)

        }
    }

}
